/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Properties;

final public class WADTools {

  //Application WADSystem path
  public static final String APP_PATH = "E:/ProjectII/WADS/WADSApp/";
  //public static final String APP_PATH = "C:/dist/app/";
  //constant for *.wde file path
  public static final String DEFAULT_WDE_PATH = "res/docs/MyDocumentTemplates";
  //HTML Document form file path
  public static final String FORM_PATH = "res/docs/HTMLForm";
  //Document Template file Extension
  public static final String DIAGRAM_FILE_EXTENSION = "wde";
  public static final String CONFIG_FILENAME = "res/wad_app.properties";
  public static final String LAST_TEMPLATE_ID_KEYNAME = "LastTemplate_ID";
  public static final int LAST_TEMPLATE_ID_DEFAULT = 0;
  public static final String SERVER_NAME_KEYNAME = "ServerName";
  public static final String SERVER_NAME_DEFAULT = "http://localhost:8084/WADSWeb";
  public static final String ACTION_NAME_KEYNAME = "ActionName";
  public static final String ACTION_NAME_DEFAULT = "servlet/submitForm";
  public static final String DBSERVER_NAME_DEFAULT = "localhost:1527";
  public static final String DB_NAME_DEFAULT = "WadsDB";
  public static final String DBSERVER_NAME_KEYNAME = "DBServer";
  //use for CONTENT_TYPE parameter of all servlets
  public static final String SERVLET_CONTENT_TYPE = "text/html; charset=UTF-8";

  public static final int TEMPLATE_ID_LEN = 6;
  public static final String ACTIVATE_DIR_PATH = "res/docs/activeDocTemplate/";
  public static final String DOC_TEMPLATE_INFO_FILENAME = "docTemplate.info";

  public static final String POWER_USER_PATH = "res/user/PowerUser/";
  public static final String RESTRICT_USER_FILE = "res/user/RestrictUser/RestrictUser.org";

  //static method for copy all files in directory
  public static boolean copyDir(File src, File dst) {
    try{
      if(!dst.getParentFile().exists())
        dst.getParentFile().mkdir();

      if(!dst.exists())
        dst.mkdir();
      System.out.println("src" + src.toString());
      File[] srcFiles = src.listFiles();
      for(int i = 0; i < srcFiles.length; i++){
        if(srcFiles[i].isFile()) {
          copyFile(srcFiles[i], new File(dst.getPath() + "/" + srcFiles[i].getName()));
        }
      }
    }
    catch(Exception e) {
        System.err.println("Exception thrown from WADTools.copyDir()");
      e.printStackTrace();
      return false;
    }
    return true;
  }

  public static void copyFile(File in, File out) throws IOException {
      if(!out.getParentFile().exists()) {
        out.getParentFile().mkdirs();
      }
      FileInputStream fis  = new FileInputStream(in);
      FileOutputStream fos = new FileOutputStream(out);
      byte[] buf = new byte[1024];
      int i = 0;
      while((i=fis.read(buf))!=-1) {
          fos.write(buf, 0, i);
      }
      fis.close();
      fos.close();
  }

  public static void deleteDIR(File dir) throws IOException {
    File[] list = dir.listFiles();
    for(int i=0; i<list.length; i++){
      list[i].delete();
    }
    dir.delete();
      System.out.println("Delete successful.");
  }


  public static String int2ConstLenString(int input, int len) {
    String st = String.valueOf(input);
    if(len < st.length()){
      return st.substring(0, len - 1);
    }
    char[] cprefix = new char[len - st.length()];
    for(int i = 0; i < cprefix.length; i++)
      cprefix[i] = '0';
    return (new String(cprefix) + st);
  }

  /**
   * @deprecated Cancel this method and we'll use database to store user profile instead.
   */
  public static boolean checkPowerUserFile(String file) {
    File f = new File(POWER_USER_PATH + file);
    if(f.exists())
      return true;
    else
      return false;
  }

  /**
   * @deprecated Cancel this method and we'll use database to store user profile instead.
   */
  public static boolean checkRestrictUserFile(){
    File f = new File(RESTRICT_USER_FILE);
    if(f.exists())
      return true;
    else
      return false;
  }

  /**
   * @deprecated None use of this method
   */
  public static void createNewOrg(File f){
    UserInfoDataStruct data = new UserInfoDataStruct("new");

    try{
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
      UserInfo ui = new UserInfo();
      ui.addData(data);
      oos.writeObject(ui);
      oos.close();
    }
    catch(Exception e){
      e.printStackTrace();
    }
  }

  /**
   * @deprecated None use of this method.
   */
  public static void createNewRestrictUserFile(boolean check){
    if(check){
      try{
        File f = new File(RESTRICT_USER_FILE);
        if(!f.exists()){
          f.createNewFile();
          WADTools.createNewOrg(f);
        }
      }
      catch(Exception e){
        e.printStackTrace();
      }
    }
    else{
      try{
        File f = new File(RESTRICT_USER_FILE);
        if(f.exists()){
          f.delete();
          f.createNewFile();
          createNewOrg(f);
        }
      }
      catch(Exception e){
        e.printStackTrace();
      }
    }
  }
  
  public static byte[] encryptPassword(char[] pw) {
    byte[] epw = null;
	  
    try{
      MessageDigest sha = MessageDigest.getInstance("SHA");
      sha.update(convertCharArray2ByteArray(pw));
      epw = sha.digest();
    }
    catch(NoSuchAlgorithmException nsae) {
        System.err.println("Exception thrown from WADTools.encryptPassword()");
      nsae.printStackTrace();
    }
    
    return epw;
  }
  
  private static byte[] convertCharArray2ByteArray(char[] ca){
    byte[] ba = new byte[ca.length];
    
    for(int i=0;i<ca.length;i++){
      ba[i] = (byte)ca[i];
    }
    
    return ba;
  }
  
  /**
   * @deprecated Cancel this method and we'll use database to store user profile instead.
   */
  public static void createNewPUnRUFile(){
    ObjectOutputStream oos;
    UserInfo PUUI = new UserInfo();
    UserInfo RUUI = new UserInfo();
    UserInfoDataStruct PUData = new UserInfoDataStruct("Powered");
    UserInfoDataStruct RUData = new UserInfoDataStruct("Restricted");
    
    PUUI.addData(PUData);
    RUUI.addData(RUData);
    
    try{
      File PUFile = new File(POWER_USER_PATH+"admin.org");
      if(PUFile.exists()){
        if(PUFile.delete() & PUFile.createNewFile()) {
            System.out.println("PU file was renewed by delete and new create.");
        }
        else {
            System.err.println("Problem occur, can't renew PU file.");
        }
      }
      else {
        if(PUFile.createNewFile()) {
            System.out.println("New PU file was created.");
        }
      }
      
      oos = new ObjectOutputStream(new FileOutputStream(PUFile));
      oos.writeObject(PUUI);
      oos.close();
    }
    catch(IOException iox) {
        System.err.println("Can't write PU infomation to PU file.");
      iox.printStackTrace();
      return;
    }
    catch(Exception e) {
      e.printStackTrace();
      return;
    }
    
      System.out.println("Power User File created.");
    
    try{
      File RUFile = new File(RESTRICT_USER_FILE);
      if(RUFile.exists()){
        if(RUFile.delete() & RUFile.createNewFile()) {
            System.out.println("RU file was renewed by delete and new create.");
        }
        else {
            System.err.println("Problem occur, can't renew PU file.");
        }
      }
      else {
        if(RUFile.createNewFile()) {
            System.out.println("New RU file was created.");
        }
      }
      
      oos = new ObjectOutputStream(new FileOutputStream(RUFile));
      oos.writeObject(RUUI);
      oos.close();
    }
    catch(IOException iox) {
        System.err.println("Can't write RU infomation to RU file.");
      iox.printStackTrace();
      return;
    }
    catch(Exception e){
      e.printStackTrace();
      return;
    }
    
      System.out.println("Restricted User File created.");
  }
	
  /**
   * Password Comparation
   */
  public static boolean isPasswordMatch(char[] pwa, char[] pwb) {
    if(pwa.length != pwb.length)
      return false;
    
    for(int i=0;i<pwa.length;i++)
      if(pwa[i] != pwb[i])
        return false;
    
    return true;
  }
  
  public static String dupHTMLSpace(String tag, int b4tag, int aftag) {
    for(int i=0;i<b4tag;i++) {
      tag = "&nbsp;" + tag;
      System.gc();
    }
    
    for(int j=0;j<aftag;j++) {
      tag = tag + "&nbsp;";
      System.gc();
    }
    
    return tag;
  }

  public static URL parseResourceFile(Object callObject, String filePath) {
    return callObject.getClass().getClassLoader().getResource(filePath);
  }
  
  public static String getCurrentDateTime() {
    Calendar current = Calendar.getInstance();
    return current.get(Calendar.YEAR)+"-"+current.get(Calendar.MONTH)+"-"+current.get(Calendar.DATE)
            +" "+current.get(Calendar.HOUR_OF_DAY)+":"+current.get(Calendar.MINUTE)+":"+current.get(Calendar.SECOND);
  }

    public static Properties loadWadConfig() {
        File configfile;
        Properties prop = new Properties();

        try {
            configfile = new File(WADTools.CONFIG_FILENAME);
            // load configure from file if file doesn't exist, load default value
            if(configfile.exists()) {
                prop.load(new FileInputStream(configfile));
            }
            else {
                prop.setProperty(WADTools.LAST_TEMPLATE_ID_KEYNAME, String.valueOf(WADTools.LAST_TEMPLATE_ID_DEFAULT));
                prop.setProperty(WADTools.SERVER_NAME_KEYNAME, WADTools.SERVER_NAME_DEFAULT);
                prop.setProperty(WADTools.ACTION_NAME_KEYNAME, WADTools.ACTION_NAME_DEFAULT);
                prop.store(new FileOutputStream(configfile), "This is default values.");
            }

            return prop;
        }
        catch(IOException iox) {
            System.err.println("Can't load configure file.");
            iox.printStackTrace(System.err);
        }

        return null;
    }

    public static void storeWadConfig(Properties wcprop) {
        try {
            wcprop.store(new FileOutputStream(new File(WADTools.CONFIG_FILENAME)), "WADS' configuration.");
        }
        catch(IOException iox) {
            System.err.println("Can't save configuration to file.");
            iox.printStackTrace(System.err);
        }
    }

    /**
     * @return the shareAppData
     */
    public static String getShareAppData() {
        System.out.println("\nGrrrrrrrrrrrr\n");
        String shareAppData = System.getenv("APPDATA")+"/Wads";
        File wadsShareRes = new File(shareAppData);
        if(!wadsShareRes.exists()) {
            wadsShareRes.mkdir();
        }

        return shareAppData;
    }

    public static void initialSharingResource() {
        System.out.println("\nArgggrrrrrrrrr\n");
//        File[] resources = new File[10];
        File shareResource = new File(getShareAppData(), CONFIG_FILENAME);
        File resource = new File(CONFIG_FILENAME);
        try {
            copyFile(resource, shareResource);
        }
        catch (IOException ex) {
            System.err.println("\n===Copying Error===");
            ex.printStackTrace(System.err);
            System.err.println("===================\n");
        }
    }
}